package com.example.administrator.myapplication;

import android.Manifest;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ManageContectActivity extends AppCompatActivity {
    private Button searchBnt, addBnt;
    private TextView resultTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_contect);
        searchBnt = (Button) findViewById(R.id.searchContactBnt);
        addBnt = (Button) findViewById(R.id.addContactBnt);
        resultTxt = (TextView) findViewById(R.id.searchResultTxt);
        searchBnt.setOnClickListener((View.OnClickListener) new SearchOnClickListener());
        addBnt.setOnClickListener(new AddOnClickListener());
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    ManageContectActivity.this, new String[]{
                            Manifest.permission.READ_CONTACTS,
                            Manifest.permission.WRITE_CONTACTS},
                    1);
                    }
                    else{
            searchBnt.setEnabled(true);
            addBnt.setEnabled(true);
        }
    }
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults){
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    searchBnt.setEnabled(true);
                    addBnt.setEnabled(true);
                }else{
                    Toast.makeText(this, "你没有同意授权", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    private class SearchOnClickListener implements View.OnClickListener {
        public void onClick(View view) {
            String resultStr = "查询结果：";
            EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
            String nameTxt = nameEdit.getText().toString();
            String condition = null;
            String[] selectionArgs = null;
            if (!nameTxt.isEmpty()) {
                condition =
                        (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) ?
                                (ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?") :
                                (ContactsContract.Contacts.DISPLAY_NAME + " LIKE ?");
                selectionArgs = new String[1];
                selectionArgs[0] = "%" + nameTxt + "%";
            }
            Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, condition, selectionArgs, null);
            int idIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            while (cursor.moveToNext()) {
                String contractId = cursor.getString(idIndex);
                String name = cursor.getString(nameIndex);
                resultStr = resultStr + "\n===" + contractId + ". " + name + "===";
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contractId, null, null);
                while (phones.moveToNext()) {
                    int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    String phoneNumber = phones.getString(numberIndex);
                    resultStr = resultStr + "\n 电话号码：" + phoneNumber;

                }
                phones.close();
                Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contractId, null, null);
                while (emails.moveToNext()) {
                    int emailIndex = emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
                    String emailAddress = emails.getString(emailIndex);
                    resultStr = resultStr + "\n 邮件地址：" + emailAddress;
                }
                emails.close();
            }
            cursor.close();
            resultTxt.setText(resultStr);
        }

    }
    private class AddOnClickListener implements View.OnClickListener {
        public void onClick(View view) {
            EditText nameEdit = (EditText) findViewById(R.id.nameEdit);
            String name = nameEdit.getText().toString();
            EditText phoneEdit = (EditText) findViewById(R.id.phoneEdit);
            String phoneNumber = phoneEdit.getText().toString();
            EditText emailEdit = (EditText) findViewById(R.id.emailEdit);
            String emailAddress = emailEdit.getText().toString();
            ContentValues values = new ContentValues();
            Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
            long rawContactId = ContentUris.parseId(rawContactUri);
            values.clear();
            values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Email.DATA, emailAddress);
            values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            resultTxt.setText("成功添加联系人：" + "\n===" + rawContactId + ". " + name + "===" + "\n 电话号码：" + phoneNumber + "\n 邮件地址：" + emailAddress);
        }
    }
}
